package cn.yanhu.kuwanapp.utils.helper

import android.content.Context
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.showToast
import com.bun.miitmdid.core.ErrorCode
import com.bun.miitmdid.core.MdidSdkHelper
import com.bun.miitmdid.interfaces.IIdentifierListener
import com.bun.miitmdid.interfaces.IdSupplier


/**
 * Created by zheng on 2019/8/22.
 */
class MiitHelper(private val appIdsUpdater: AppIdsUpdater?) : IIdentifierListener {
    /*
     * 方法调用
     */
    fun callFromReflect(cxt: Context?) {
        val nres = MdidSdkHelper.InitSdk(cxt, true, this)
        if (nres == ErrorCode.INIT_ERROR_DEVICE_NOSUPPORT) { //不支持的设备
            showToast("${nres} 不支持的设备")
            logcom("${nres} 不支持的设备")
        } else if (nres == ErrorCode.INIT_ERROR_LOAD_CONFIGFILE) { //加载配置文件出错
            showToast("${nres} 不支持的设备")
            logcom("${nres} 不支持的设备")
        } else if (nres == ErrorCode.INIT_ERROR_MANUFACTURER_NOSUPPORT) { //不支持的设备厂商
            showToast("${nres} 不支持的设备")
        } else if (nres == ErrorCode.INIT_ERROR_RESULT_DELAY) { //获取接口是异步的，结果会在回调中返回，回调执行的回调可能在工作线程
            logcom("${nres} 获取设备信息失败，请稍后重试")
        } else if (nres == ErrorCode.INIT_HELPER_CALL_ERROR) { //反射调用出错
            showToast("${nres} 不支持的设备")
            logcom("${nres} 不支持的设备")
        }
    }

    private var isDeviceSupported = false


    interface AppIdsUpdater {
        fun OnIdsAvalid(isSupport: Boolean, oaid: String, vaid: String, aaid: String)
    }

    override fun OnSupport(isSupported: Boolean, supplier: IdSupplier?) {
        try {
            if (supplier == null) {
                logcom("onSupport: supplier is null")
                return
            }
            if (appIdsUpdater == null) {
                logcom("onSupport: callbackListener is null")
                return
            }
            // 临时修复1.0.26版本BUG-001: 部分品牌机型 isSupport=true 后，大约5s后会再次回调 isSupport=false
            if (supplier.isSupported) {
                isDeviceSupported = true
            } else if (isDeviceSupported) {
                return
            }
            var oaid = ""
            var vaid = ""
            var aaid = ""
            oaid = supplier.oaid
            vaid = supplier.vaid
            aaid = supplier.aaid
            appIdsUpdater.OnIdsAvalid(isSupported, oaid, vaid, aaid)
        } catch (e: Exception) {
            appIdsUpdater?.OnIdsAvalid(false, "", "", "")
        }
    }


}